package Frames;

import Classes.Cliente;
import Classes.Usuario;
import Classes_Conexao.ClienteDAO;
import Classes_Conexao.UsuarioDAO;
import java.awt.Dimension;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Saulo Queiroz
 */
public class CadastroUsuario extends javax.swing.JInternalFrame {

    Usuario usuario = new Usuario();
    private DefaultTableModel modelo = null;

    public CadastroUsuario() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnIncluir = new javax.swing.JButton();
        btnLocalizar = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        btnGravar = new javax.swing.JButton();
        btnFechar = new javax.swing.JButton();
        btnNaoGravar = new javax.swing.JButton();
        Localizar = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        txtPesquisa = new javax.swing.JTextField();
        CadastroUsuario = new javax.swing.JPanel();
        txtSenha = new javax.swing.JPasswordField();
        txtLogin = new javax.swing.JTextField();
        txtNome = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro de Funcionario");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
        });

        btnIncluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/New-icon.png"))); // NOI18N
        btnIncluir.setText("Incluir");
        btnIncluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnIncluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnIncluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIncluirActionPerformed(evt);
            }
        });

        btnLocalizar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/Search-icon.png"))); // NOI18N
        btnLocalizar.setText("Localizar");
        btnLocalizar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnLocalizar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnLocalizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLocalizarActionPerformed(evt);
            }
        });

        btnExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/Delete-icon.png"))); // NOI18N
        btnExcluir.setText("Excluir");
        btnExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        btnGravar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/Save-icon.png"))); // NOI18N
        btnGravar.setText("Gravar");
        btnGravar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGravar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGravarActionPerformed(evt);
            }
        });

        btnFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/Log-Out-icon.png"))); // NOI18N
        btnFechar.setText("Fechar");
        btnFechar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnFechar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFecharActionPerformed(evt);
            }
        });

        btnNaoGravar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/Remove-icon.png"))); // NOI18N
        btnNaoGravar.setText("Não Gravar");
        btnNaoGravar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnNaoGravar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnNaoGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNaoGravarActionPerformed(evt);
            }
        });

        Localizar.setBorder(javax.swing.BorderFactory.createTitledBorder("Localizar"));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Pesquisa"));

        txtPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPesquisaKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(txtPesquisa, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(txtPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout LocalizarLayout = new javax.swing.GroupLayout(Localizar);
        Localizar.setLayout(LocalizarLayout);
        LocalizarLayout.setHorizontalGroup(
            LocalizarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(LocalizarLayout.createSequentialGroup()
                .addGroup(LocalizarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(LocalizarLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 556, Short.MAX_VALUE))
                    .addGroup(LocalizarLayout.createSequentialGroup()
                        .addGap(109, 109, 109)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        LocalizarLayout.setVerticalGroup(
            LocalizarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(LocalizarLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(24, 24, 24)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(42, Short.MAX_VALUE))
        );

        CadastroUsuario.setBorder(javax.swing.BorderFactory.createTitledBorder("Cadastro"));

        txtLogin.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtLoginKeyTyped(evt);
            }
        });

        txtNome.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNomeKeyTyped(evt);
            }
        });

        jLabel3.setText("Senha");

        jLabel2.setText("Login");

        jLabel1.setText("Nome");

        javax.swing.GroupLayout CadastroUsuarioLayout = new javax.swing.GroupLayout(CadastroUsuario);
        CadastroUsuario.setLayout(CadastroUsuarioLayout);
        CadastroUsuarioLayout.setHorizontalGroup(
            CadastroUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(CadastroUsuarioLayout.createSequentialGroup()
                .addGroup(CadastroUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(txtNome, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(CadastroUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(CadastroUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        CadastroUsuarioLayout.setVerticalGroup(
            CadastroUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(CadastroUsuarioLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(CadastroUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(CadastroUsuarioLayout.createSequentialGroup()
                        .addGroup(CadastroUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(CadastroUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(CadastroUsuarioLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(btnIncluir, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(9, 9, 9)
                .addComponent(btnLocalizar, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(9, 9, 9)
                .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addComponent(btnGravar, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addComponent(btnNaoGravar)
                .addGap(6, 6, 6)
                .addComponent(btnFechar, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(CadastroUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(Localizar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnIncluir)
                    .addComponent(btnLocalizar)
                    .addComponent(btnExcluir)
                    .addComponent(btnGravar)
                    .addComponent(btnNaoGravar)
                    .addComponent(btnFechar))
                .addGap(18, 18, 18)
                .addComponent(CadastroUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(Localizar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIncluirActionPerformed
        if (btnLocalizar.getText().equals("Voltar")) {
            btnLocalizar.setText("Localizar");
            CadastroUsuario.setVisible(true);
            Localizar.setVisible(false);
        } else {
            btnLocalizar.setText("Localizar");
            CadastroUsuario.setVisible(true);
            Localizar.setVisible(false);
        }
        txtNome.setText("");
        txtLogin.setText("");
        txtSenha.setText("");

        //desativar e ativar
        btnIncluir.setEnabled(false);
        btnLocalizar.setEnabled(false);
        btnExcluir.setEnabled(false);
        btnGravar.setEnabled(true);
        btnNaoGravar.setEnabled(true);
        btnFechar.setEnabled(false);


        //ativar e desativar campos
        txtNome.setEnabled(true);
        txtLogin.setEnabled(true);
        txtSenha.setEnabled(true);
        //mudar nome de botões
        btnGravar.setText("Gravar");
}//GEN-LAST:event_btnIncluirActionPerformed

    private void btnLocalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLocalizarActionPerformed
        if (btnLocalizar.getText().equals("Localizar")) {
            btnLocalizar.setText("Voltar");
            CadastroUsuario.setVisible(false);
            Localizar.setVisible(true);
            btnIncluir.setEnabled(false);
            try {
                UsuarioDAO usuarioDao = new UsuarioDAO();
                ArrayList<Usuario> usuario = usuarioDao.retornaTodosUsuarios();

                modelo.setNumRows(0);

                for (Usuario u : usuario) {
                    modelo.addRow(new String[]{Integer.toString(u.getCodigo()), u.getNome(), u.getLogin()});
                }

            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } else {
            btnLocalizar.setText("Localizar");
            CadastroUsuario.setVisible(true);
            Localizar.setVisible(false);
            btnIncluir.setEnabled(true);
        }
        btnExcluir.setEnabled(false);
        btnGravar.setText("Gravar");
    }//GEN-LAST:event_btnLocalizarActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        UIManager.put("OptionPane.yesButtonText", "Sim");
        UIManager.put("OptionPane.noButtonText", "Não");
        UIManager.put("OptionPane.cancelButtonText", "Cancelar");
        int resultado = JOptionPane.showConfirmDialog(null, "Você deseja realmente excluir?", "Excluir", 1, 1);
        if (resultado == 0) {
            int linhaSelecionada = jTable1.getSelectedRow();
            Usuario usuario = new Usuario();

            usuario.setNome(jTable1.getValueAt(linhaSelecionada, 1).toString());

            try {
                UsuarioDAO usuarioDao = new UsuarioDAO();
                usuarioDao.excluir(usuario);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            modelo.removeRow(linhaSelecionada);
            // ativar e desativar os campos de texto
            txtNome.setText("");
            txtLogin.setText("");
            txtSenha.setText("");
            //ativar e desativar campos
            txtNome.setEnabled(false);
            txtLogin.setEnabled(false);
            txtSenha.setEnabled(false);
            // desativar o botao excluir
            btnExcluir.setEnabled(false);
        } else {
            return;
        }
    }//GEN-LAST:event_btnExcluirActionPerformed

    private void btnGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGravarActionPerformed
        if (btnGravar.getText() == "Atualizar") {
            //alterar
            int linhaSelecionada = jTable1.getSelectedRow();
            Usuario usuario = new Usuario();

            usuario.setCodigo(Integer.parseInt(jTable1.getValueAt(linhaSelecionada, 0).toString())); //"Aqui é para modificação do id (Não pode ser alterado.)"
            usuario.setNome(txtNome.getText());
            usuario.setLogin(txtLogin.getText());
            //usuario.setSenha(txtSenha.getText());
            try {
                UsuarioDAO uDao = new UsuarioDAO();
                uDao.editar(usuario);

            } catch (Exception e) {
                e.printStackTrace();
            }
            btnGravar.setEnabled(false);
        } else {
            //adiciona
            if (txtNome.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "O campo Nome não pode ficar em branco");
                txtNome.requestFocus();
                return;
            }


            if (txtLogin.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "O campo Login não pode ficar em branco");
                txtLogin.requestFocus();
                return;
            }
            try {
                UsuarioDAO uDao = new UsuarioDAO();
                Usuario u = new Usuario();
                u.setLogin(txtLogin.getText());

                ArrayList<Usuario> lista = uDao.buscaLogin(u);

                if (lista.size() > 0) {
                    JOptionPane.showMessageDialog(null, "Já Existe um Registro com Esse Login!");
                    return;
                } else {
                    usuario.setLogin(txtLogin.getText());
                }
            } catch (SQLException sqle) {
                sqle.printStackTrace();
            }

            if (txtSenha.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "O campo Senha não pode ficar em branco");
                txtSenha.requestFocus();
                return;
            }

            usuario.setNome(txtNome.getText());
            usuario.setSenha(txtSenha.getText());


            //conexão com o banco!
            UsuarioDAO dao = null;

            try {
                dao = new UsuarioDAO();
                // se caso ocorrer um erro ele vai entrar no catch
                txtNome.setText("");
                txtLogin.setText("");
                txtSenha.setText("");
            } catch (SQLException ex) {
                Logger.getLogger(CadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                dao.adiciona(usuario);
                // se caso ocorrer um erro ele vai entrar no catch
                txtNome.setText("");
                txtLogin.setText("");
                txtSenha.setText("");
            } catch (SQLException ex) {
                Logger.getLogger(CadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
            }
            //fim adiciona
            //ativo e não ativo
            btnNaoGravar.setEnabled(false);
            btnGravar.setEnabled(false);
            btnIncluir.setEnabled(true);
            btnLocalizar.setEnabled(true);
            btnFechar.setEnabled(true);
        }

}//GEN-LAST:event_btnGravarActionPerformed

    private void btnFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFecharActionPerformed
        this.dispose();
}//GEN-LAST:event_btnFecharActionPerformed

    private void btnNaoGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNaoGravarActionPerformed
        txtNome.setText("");
        txtLogin.setText("");
        txtSenha.setText("");
        //ativar e desativar botões
        btnNaoGravar.setEnabled(false);
        btnGravar.setEnabled(false);
        btnIncluir.setEnabled(true);
        btnLocalizar.setEnabled(true);
        btnFechar.setEnabled(true);
}//GEN-LAST:event_btnNaoGravarActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        if (evt.getClickCount() == 2) {
            if (jTable1.getSelectedRow() != -1) {
                int linhaSelecionada = jTable1.getSelectedRow();
                //txtCodigo.setText(modelo.getValueAt(linhaSelecionada, 0).toString());
                txtNome.setText(modelo.getValueAt(linhaSelecionada, 1).toString());
                txtLogin.setText(modelo.getValueAt(linhaSelecionada, 2).toString());
                // txtSenha.setText((modelo.getValueAt(linhaSelecionada, 3).toString()));

                CadastroUsuario.setVisible(true);
                Localizar.setVisible(false);
                // ativar campos para edição
                txtNome.setEnabled(true);
                txtLogin.setEnabled(true);
                txtSenha.setEnabled(false);
                //ativar e desativar botão
                btnExcluir.setEnabled(true);
                btnIncluir.setEnabled(true);
                btnGravar.setText("Atualizar");

                if (btnLocalizar.getText().equals("Localizar")) {
                    btnLocalizar.setText("Voltar");
                    CadastroUsuario.setVisible(false);
                    Localizar.setVisible(true);
                } else {
                    btnLocalizar.setText("Localizar");
                    CadastroUsuario.setVisible(true);
                    Localizar.setVisible(false);
                }
            }
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
    }//GEN-LAST:event_formWindowOpened

    private void txtPesquisaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPesquisaKeyReleased
        modelo.setNumRows(0);

        try {
            UsuarioDAO uDao = new UsuarioDAO();
            ArrayList<Usuario> usuario = uDao.retornaUsuarioPorNome(txtPesquisa.getText());

            for (Usuario u : usuario) {
                modelo.addRow(new String[]{Integer.toString(u.getCodigo()), u.getNome(), u.getLogin()});
            }
        } catch (SQLException ex) {
            ex.printStackTrace();

        }
}//GEN-LAST:event_txtPesquisaKeyReleased

    private void txtNomeKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNomeKeyTyped
        btnGravar.setEnabled(true);
    }//GEN-LAST:event_txtNomeKeyTyped

    private void txtLoginKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtLoginKeyTyped
        btnGravar.setEnabled(true);
    }//GEN-LAST:event_txtLoginKeyTyped

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
        // DIMENSÕES DA TELA
        // Recupera o tamanho da tela
        java.awt.Dimension screenSize =
                java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        // Ajusta o tamanho da janela (JFrame)
        setSize(new java.awt.Dimension(680, 537));
        // Ajusta a localização da janela, dependendo do tamanho da janela em
        // relação ao tamanho da tela
        setLocation((screenSize.width - 980) / 2, (screenSize.height - 800) / 2);

        //ativar e desativar botões
        btnIncluir.setEnabled(true);
        btnLocalizar.setEnabled(true);
        btnExcluir.setEnabled(false);
        btnGravar.setEnabled(false);
        btnNaoGravar.setEnabled(false);
        //ativar e desativar campos
        txtNome.setEnabled(false);
        txtLogin.setEnabled(false);
        txtSenha.setEnabled(false);
        Localizar.setVisible(false);
        CadastroUsuario.setVisible(true);


        //TABELA
        String[] colunas = new String[]{"", "", ""};
        String[][] dados = new String[][]{};


        modelo = new DefaultTableModel(dados, colunas) {

            public boolean isCellEditable(int row, int col) {
                return false;
            }
        };
        jTable1.setModel(modelo);
        jTable1.getTableHeader().getColumnModel().getColumn(0).setHeaderValue("Código");
        jTable1.getTableHeader().getColumnModel().getColumn(1).setHeaderValue("Nome");
        jTable1.getTableHeader().getColumnModel().getColumn(2).setHeaderValue("Login");

        jTable1.getTableHeader().getColumnModel().getColumn(0).setMinWidth(40);
        jTable1.getTableHeader().getColumnModel().getColumn(1).setMinWidth(180);
        jTable1.getTableHeader().getColumnModel().getColumn(2).setMinWidth(130);

        jTable1.setPreferredScrollableViewportSize(new Dimension(350, 0));


        try {
            UsuarioDAO usuarioDao = new UsuarioDAO();
            ArrayList<Usuario> usuario = usuarioDao.retornaTodosUsuarios();

            modelo.setNumRows(0);

            for (Usuario u : usuario) {
                modelo.addRow(new String[]{Integer.toString(u.getCodigo()), u.getNome(), u.getLogin()});
            }

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_formInternalFrameOpened

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CadastroUsuario().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel CadastroUsuario;
    private javax.swing.JPanel Localizar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnFechar;
    private javax.swing.JButton btnGravar;
    private javax.swing.JButton btnIncluir;
    private javax.swing.JButton btnLocalizar;
    private javax.swing.JButton btnNaoGravar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField txtLogin;
    private javax.swing.JTextField txtNome;
    private javax.swing.JTextField txtPesquisa;
    private javax.swing.JPasswordField txtSenha;
    // End of variables declaration//GEN-END:variables
}
